//
//  MessageHandlerController.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/6/4.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import YYText

class MessageHandlerController: UIViewController {
    @IBOutlet weak var timeLabel: UILabel!
    
    @IBOutlet weak var closeBtn: UIButton!
    @IBOutlet weak var titleLabel: UILabel!
    
    @IBOutlet weak var descriptionView: UILabel!
    var jbtitles = ["申请加班：","项目编号：","加班日期：","起始时间：","申请记工：","加班原因："]
    var jbvalues:[String] = [String]()
    
    lazy var jbStackView:UIStackView = {
        var view = UIStackView()
        view.axis = .vertical
        view.distribution = .fill
        view.alignment = .fill
        view.spacing = 0
        return view
    }()
    
    lazy var operateStackView:UIStackView = {
        var view = UIStackView()
        view.axis = .horizontal
        view.distribution = .fillEqually
        view.alignment = .fill
        view.spacing = 10
        return view
    }()
    
    lazy var bqlayout:UIView = {
        var view = UIView()
        view.backgroundColor = UIColor.white
        view.angle = 10
        view.addSubview(self.qtTextView)
        view.addSubview(self.tellBtn)
        return view
    }()
    
    lazy var qtTextView:UILabel = {
        var view = UILabel()
        view.textColor = UIColor.DeepBlack
        view.numberOfLines = 0
        return view
    }()
    lazy var tellBtn:UIButton = {
        var view = UIButton()
        view.tag = 2
        view.setTitleColor(UIColor.LightBlue, for: .normal)
        view.setImage(UIImage(named: "tellgreen"), for: .normal)
        view.addTarget(self, action: #selector(btnClick(_:)), for: UIControlEvents.touchUpInside)
        return view
    }()
    
    lazy var submitBtn:UIButton = {
        var view = UIButton(type: UIButtonType.custom)
        view.setTitle("同意", for: .normal)
        view.setTitleColor(UIColor.white, for: .normal)
        view.tag = 0
        view.angle = 2
        view.contentEdgeInsets = UIEdgeInsetsMake(5, 0, 5, 0)
        view.setBackgroundImage(UIColor.LightBlue.createImageWithColor(), for: .normal)
        view.addTarget(self, action: #selector(btnClick(_:)), for: UIControlEvents.touchUpInside)
        return view
    }()
    lazy var backBtn:UIButton = {
        var view = UIButton(type: UIButtonType.custom)
        view.setTitle("退回", for: .normal)
        view.setTitleColor(UIColor.white, for: .normal)
        view.tag = 1
        view.angle = 2
        view.contentEdgeInsets = UIEdgeInsetsMake(5, 0, 5, 0)
        view.setBackgroundImage(UIColor.orange.createImageWithColor(), for: .normal)
        view.addTarget(self, action: #selector(btnClick(_:)), for: UIControlEvents.touchUpInside)
        return view
    }()
    var detailBean:MessageDetailBean?
    var detailStatus:MessageStatue?
    
    var itemModel:MessageItem?
    var jsonParams:Dictionary<String,Any>?
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.initView()
        //self.addJBView()
        //self.addOperateBtn();
        self.getMsgDetail()
        self.getMsgStatus()

        // Do any additional setup after loading the view.
    }
    func initView(){
        self.closeBtn.tag = 3
        self.closeBtn.imageView?.contentMode = .scaleToFill
        self.closeBtn.addTarget(self, action: #selector(btnClick(_:)), for: UIControlEvents.touchUpInside)
        let type = self.jsonParams!["Type"] as? String ?? ""
        if type == "劳务公司-补签申请"{
            self.titleLabel.text = "补签申请"
            let days = (jsonParams!["Params"] as! Dictionary<String,Any>)["WorkDays"] as? String
            let hours = (jsonParams!["Params"] as! Dictionary<String,Any>)["WorkHours"] as? String
            var d:String?
            if WorkType == 2{
                d = String.init(format: "%@\n补签工时：%@小时", self.itemModel?.Description ?? "",hours ?? "0")
            }else{
                d = String.init(format: "%@\n补签工数：%@工",self.itemModel?.Description ?? "",days ?? "0")
            }
            self.descriptionView.text = d
            
        }else if type == "劳务公司-调入申请"{
            self.titleLabel.text = "调入申请"
        }else if type == "劳务公司-考勤异常"{
            self.titleLabel.text = "考勤异常"
        }else if type == "劳务公司-记工申请"{
            self.titleLabel.text = "记工申请"
            let days = (self.jsonParams!["Params"] as! Dictionary<String,Any>)["WorkDays"] as? String
            let hours = (self.jsonParams!["Params"] as! Dictionary<String,Any>)["WorkHours"] as? String
            
            let d = String.init(format:"%@\n计算工数：%@工\n申请计工：%@工",self.itemModel?.Description ?? "",days ?? "0",hours ?? "0")
            self.descriptionView.text = d
            
        }else if type == "劳务公司-加班申请"{
            self.titleLabel.text = "加班申请"
        }
        
        self.timeLabel.text = (self.itemModel?.CreateTime ?? "").getSubstring(0, end: 10)
    
        
    }
    
    func getMsgDetail(){
        var params:[String:Any] = ["procNoticeId":self.itemModel!.ID ?? ""]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .MessageDetail, params: &params, type: MessageDetailBean.self, success: { (bean,dic) in
            self.detailBean = bean as? MessageDetailBean
            let type = (dic["Result"] as! Dictionary<String,Any>)["Type"] as? String ?? ""
            if type == "劳务公司-补签申请"{
                var signdate = self.detailBean?.Result?.Params?.SignedDate ?? ""
                self.descriptionView.text?.append(String.init(format:"\n补签日期：%@\n补签项目：%@",signdate.getSubstring(0, end: signdate.count - 7),self.detailBean?.Result?.Params?.ProjectName ?? ""))//Result.Params.SignedDate
                self.addBqLayout()
            }else if type == "劳务公司-调入申请"{
                self.descriptionView.text = String.init(format: "%@\n调入项目：%@",  self.itemModel?.Description ?? "",self.detailBean?.Result?.Params?.ProjectName ?? "")
            }else if type == "劳务公司-加班申请"{
                var bqdate = self.detailBean?.Result?.Params?.WorkDate ?? ""
                self.descriptionView.text = self.itemModel?.Description ?? ""
                self.jbvalues.append(self.detailBean?.Result?.Params?.ProjectName ?? "")
                self.jbvalues.append(self.detailBean?.Result?.Params?.OrderNo ?? "")
                self.jbvalues.append(bqdate.getSubstring(0, end: bqdate.count - 7))
                self.jbvalues.append((self.detailBean?.Result?.Params?.WorkBeginTime ?? "").getSubstring(0, end: 19))
                self.jbvalues.append(String.init(format: "%@工", self.detailBean?.Result?.Params?.ApplyWorkDays ?? ""))
                self.jbvalues.append(self.detailBean?.Result?.Params?.Reason ?? "")
                self.addJBView()
            }
            
        }) { (error) in
            QWTextWithStatusHud("网络异常", target: self.view)
            /*DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: {
                self.dismiss(animated: true, completion: nil)
            })*/
        }
    }
    
    func getMsgStatus(){
        var params:[String:Any] = ["orderDataId":self.itemModel!.OrderDataID ?? ""]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .MessageStatus, params: &params, type: MessageStatue.self, success: { (bean,dic) in
            self.detailStatus = bean as? MessageStatue
            self.addOperateBtn()
            
        }) { (error) in
            switch error{
            case .StateFail(let dic):
                guard let t = dic as? Dictionary<String,Any> else{
                    return
                }
                if t["State"] as? String != "OK"{
                    var r = MessageStatusResult(PageName: (t["Result"] as! Dictionary<String,Any>)["PageName"] as? String ?? "", OrderConfigId: (t["Result"] as! Dictionary<String,Any>)["OrderConfigId"] as? String ?? "", OrderId: (t["Result"] as! Dictionary<String,Any>)["OrderId"] as? String ?? "", JsonData: (t["Result"] as! Dictionary<String,Any>)["JsonData"] as? String ?? "", WorkflowState: (t["Result"] as! Dictionary<String,Any>)["WorkflowState"] as? String ?? "")
                    self.detailStatus = MessageStatue(State: "Fail", Result: r)
                    self.addOperateResult()
                }
                break
            case .HTTPERROR:
                break
            case .DATAERROR:
                break
            case .DATAFAIL:
                break
            }
        }
    }
    
    //true:同意  false：拒绝
    func operate(_ flag:Bool){
        
    }
    
    func disagressOperate(){
        QWTextWithStatusHud("正在处理...", target: self.view)
        var params:[String:Any] = ["pageName":self.detailStatus?.Result?.PageName ?? "","orderConfigId":self.detailStatus?.Result?.OrderConfigId ?? "","orderId":self.detailStatus?.Result?.OrderId ?? "","jsonData":self.detailStatus?.Result?.JsonData ?? "","approvalNote":"退回","carbonList":"","isBackTrack":"false"]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .MessageDisAgress, params: &params, type: MessageCheckResult.self, success: { (bean, _) in
            
        }) { (error) in
            QWHudDiss(self.view)
            switch error{
            case .StateFail(let str):
                guard var t = str as? String else{
                    return
                }
                if t == "OK"{
                    QWTextonlyHud("操作成功", target: self.view)
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2, execute: {
                        self.dismiss(animated: true, completion: nil)
                    })
                }
                
                break
                
            case .HTTPERROR:
                break
            case .DATAERROR:
                break
            case .DATAFAIL:
                break
            }
            
        }
    }
    
    func agressOperate(){
        QWTextWithStatusHud("正在处理...", target: self.view)
        var params:[String:Any] = ["pageName":self.detailStatus?.Result?.PageName ?? "","orderConfigId":self.detailStatus?.Result?.OrderConfigId ?? "","orderId":self.detailStatus?.Result?.OrderId ?? "","jsonData":self.detailStatus?.Result?.JsonData ?? "","approvalNote":"同意","carbonList":"","isBackTrack":"false"]
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .MessageAgress, params: &params, type: MessageCheckResult.self, success: { (bean, _) in
            
        }) { (error) in
            QWHudDiss(self.view)
            switch error{
            case .StateFail(let str):
                guard var t = str as? String else{
                    return
                }
                if t == "OK"{
                    QWTextonlyHud("操作成功", target: self.view)
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+2, execute: {
                        self.dismiss(animated: true, completion: nil)
                    })
                }
                
                break
                
            case .HTTPERROR:
                break
            case .DATAERROR:
                break
            case .DATAFAIL:
                break
            }
            
        }
    }
    
    @objc func btnClick(_ sender:UIButton){
        switch sender.tag {
        case 0:
            print("同意")
            self.agressOperate()
            break
        case 1:
            print("退回")
            self.disagressOperate()
            break
        case 2:
            UIApplication.shared.openURL(URL(string: "telprompt:\(self.detailBean?.Result?.Params?.ContactPhone ?? "")")!)
            break
        case 3:
            self.dismiss(animated: true, completion: nil)
            break
        default:
            break
        }
    }
    
    
    //加班申请内容
    func addJBView(){
        self.view.addSubview(self.jbStackView)
        self.jbtitles.enumerated().forEach { (position,item) in
            var label1 = UILabel()
            label1.text = item
            label1.textColor = UIColor.DeepBlack
            var label2 = UILabel()
            label2.text = self.jbvalues[position]
            label2.numberOfLines = 0
            label2.textColor = UIColor.DeepBlack
            var containview = UIView()
            containview.backgroundColor = UIColor.white
            containview.addSubview(label1)
            containview.addSubview(label2)
            label1.snp.updateConstraints({ (make) in
                make.top.equalTo(containview.snp.top).offset(2)
                make.bottom.equalTo(containview.snp.bottom).offset(-2)
                make.left.equalTo(containview.snp.left).offset(2)
            })
            label2.snp.updateConstraints({ (make) in
                make.left.equalTo(label1.snp.right).offset(2)
                make.right.equalTo(containview.snp.right).offset(-2)
                make.top.equalTo(containview.snp.top).offset(2)
                make.bottom.equalTo(containview.snp.bottom).offset(-2)
            })
            self.jbStackView.addArrangedSubview(containview)
        }
        
        self.jbStackView.snp.updateConstraints { (make) in
            make.left.equalTo(self.view.snp.left).offset(10)
            make.right.equalTo(self.view.snp.right).offset(-10)
            make.top.equalTo(self.descriptionView.snp.bottom).offset(10)
        }
        
        
        
    }
    //同意取消按钮
    func addOperateBtn(){
        self.view.addSubview(self.operateStackView)
        self.operateStackView.addArrangedSubview(self.submitBtn)
        self.operateStackView.addArrangedSubview(self.backBtn)
        self.operateStackView.snp.updateConstraints { (make) in
            make.left.equalTo(self.view).offset(15)
            make.right.equalTo(self.view).offset(-15)
            make.bottom.equalTo(self.view).offset(-15)
        }
    }
    
    //添加处理结果
    func addOperateResult(){
        var result:YYLabel = YYLabel()
        result.textContainerInset = UIEdgeInsetsMake(10, 15, 10, 15)
        result.textAlignment = .center
        result.textVerticalAlignment = .center
        var attr:NSMutableAttributedString = NSMutableAttributedString(string: String.init(format: "    %@    ", self.detailStatus?.Result?.WorkflowState ?? ""), attributes: [NSAttributedStringKey.font : UIFont.init(name: "Arial-BoldMT", size: CGFloat(18)),NSAttributedStringKey.foregroundColor:UIColor.white])
        attr.yy_textBackgroundBorder = YYTextBorder.init(fill: UIColor.gray.withAlphaComponent(0.6), cornerRadius: 5)
        
        result.attributedText = attr
        self.view.addSubview(result)
        result.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view.snp.bottom).offset(-10)
            make.centerX.equalTo(self.view)
        }
    }
    
    //补签申请
    func addBqLayout(){
        self.view.addSubview(self.bqlayout)
        self.qtTextView.text = String.init(format: "补签原因：%@", self.detailBean?.Result?.Params?.SupplementReason ?? "")//
        self.tellBtn.setTitle(self.detailBean?.Result?.Params?.ContactPhone ?? "", for: .normal)
        self.bqlayout.snp.updateConstraints { (make) in
            make.top.equalTo(self.descriptionView.snp.bottom).offset(10)
            make.left.equalTo(self.view.snp.left).offset(10)
            make.right.equalTo(self.view.snp.right).offset(-10)
        }
        self.qtTextView.snp.updateConstraints { (make) in
            make.top.equalTo(self.bqlayout.snp.top).offset(10)
            make.left.equalTo(self.bqlayout.snp.left).offset(10)
            make.right.equalTo(self.bqlayout.snp.right).offset(-10)
        }
        
        self.tellBtn.snp.updateConstraints { (make) in
            make.top.equalTo(self.qtTextView.snp.bottom).offset(70)
            make.bottom.equalTo(self.bqlayout.snp.bottom).offset(-10)
            make.centerX.equalTo(self.bqlayout)
        }
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
